package com.yhsoft.buyer.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsoft.benefitcard.entity.BatchGoods;
import com.yhsoft.benefitcard.entity.CardsBatch2;
import com.yhsoft.benefitcard.entity.CardsInfo;
import com.yhsoft.benefitcard.service.IBatchGoodsService;
import com.yhsoft.benefitcard.service.ICardsBatch2Service;
import com.yhsoft.benefitcard.service.ICardsInfoService;
import com.yhsoft.bill.controller.response.SalerCwtjOutVo;
import com.yhsoft.buyer.controller.Po.SkuPo;
import com.yhsoft.buyer.controller.request.DeliveryInVo;
import com.yhsoft.buyer.controller.request.OrdersDyInVo;
import com.yhsoft.buyer.controller.request.VenderOrdersInVo;
import com.yhsoft.buyer.controller.response.*;
import com.yhsoft.buyer.entity.*;
import com.yhsoft.buyer.mapper.BuyerCartMapper;
import com.yhsoft.buyer.mapper.BuyerCartSkuMapper;
import com.yhsoft.buyer.mapper.BuyerOrderMapper;
import com.yhsoft.buyer.service.*;
import com.yhsoft.common.service.FuSiLingFlimApiService;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.common.utils.IDGenerator;
import com.yhsoft.flim.controller.response.DYOrderOutVo;
import com.yhsoft.flim.controller.response.FlimPayOutVo;
import com.yhsoft.goods.entity.*;
import com.yhsoft.goods.mapper.CompanySkuChargeMapper;
import com.yhsoft.goods.mapper.GoodSkuMapper;
import com.yhsoft.goods.mapper.GoodsInfoMapper;
import com.yhsoft.goods.mapper.SkuInfoMapper;
import com.yhsoft.goods.service.ICompanyGoodsService;
import com.yhsoft.sys.controller.Response.OrderIdsOutVo;
import com.yhsoft.sys.controller.Response.UserOrderInfoOutVo;
import com.yhsoft.sys.entity.CompanyInfo;
import com.yhsoft.sys.entity.WorkOrderInfo;
import com.yhsoft.sys.service.ICompanyInfoService;
import com.yhsoft.sys.service.IWorkOrderInfoService;
import com.yhsoft.wxprogram.controller.request.FlkPayInVo;
import com.yhsoft.wxprogram.controller.response.BenefitCardOutVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-09-26
 */
@Service
@Slf4j
public class BuyerOrderServiceImpl extends ServiceImpl<BuyerOrderMapper, BuyerOrder> implements IBuyerOrderService {
    @Resource
    private IBuyerAddressService iBuyerAddressService;

    @Resource
    private BuyerCartMapper buyerCartMapper;

    @Resource
    private SkuInfoMapper skuInfoMapper;

    @Resource
    private GoodSkuMapper goodSkuMapper;

    @Resource
    private BuyerCartSkuMapper buyerCartSkuMapper;

    @Resource
    private ICardsInfoService iCardsInfoService;

    @Resource
    private ICompanyGoodsService iCompanyGoodsService;

    @Resource
    private IBatchGoodsService iBatchGoodsService;

    @Resource
    private ICardsBatch2Service iCardsBatch2Service;

    @Resource
    private ICompanyInfoService iCompanyInfoService;

    @Resource
    private GoodsInfoMapper goodsInfoMapper;

    @Resource
    private IWorkOrderInfoService iWorkOrderInfoService;

    @Resource
    private BuyerOrderMapper buyerOrderMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IOrderCardService iOrderCardService;

    @Resource
    private CompanySkuChargeMapper companySkuChargeMapper;

    @Override
    public OrderDetailOutVo detail(String orderId) {
        BuyerOrder buyerOrder = this.baseMapper.selectById(orderId);
        OrderDetailOutVo outVo = new OrderDetailOutVo();
        if (buyerOrder.getAddressId() != null) {
            BuyerAddress buyerAddress = iBuyerAddressService.getById(buyerOrder.getAddressId());

            BuyerAddressOutVo buyerAddressOutVo = new BuyerAddressOutVo();
            BeanUtils.copyProperties(buyerAddress, buyerAddressOutVo);

            outVo.setCartOutVo(getCartOutVo(buyerOrder.getCartId()));
            outVo.setBuyerAddressOutVo(buyerAddressOutVo);
        } else {
            outVo.setFlimInfo(buyerOrder.getFlimInfo());
            outVo.setPoster(buyerOrder.getPoster());
            outVo.setFlimTicketInfo(buyerOrder.getFlimTicketInfo());
        }

        outVo.setTotlePrice(buyerOrder.getTotalPrice());
        outVo.setCreateTime(buyerOrder.getCreateTime());
        outVo.setExpressTime(buyerOrder.getExpressTime());
        // 待完善
        outVo.setTotleYF(new BigDecimal(0));
        outVo.setPayMethod(buyerOrder.getPayMethod());
        outVo.setPayTime(buyerOrder.getPayTime());
        outVo.setEndTime(buyerOrder.getEndTime());
        outVo.setOrderStatus(buyerOrder.getOrderStatus());
        outVo.setPayPrice(buyerOrder.getTotalPrice());
        outVo.setOrderId(orderId);
        outVo.setCardPrice(buyerOrder.getCardPrice());
        outVo.setPayablePrice(buyerOrder.getPayablePrice());
        return outVo;
    }

    @Override
    @Transactional
    public CheckOutVo checkout(Integer cartId, Integer addressId) {
        // 价格计算
        BuyerCart buyerCart = buyerCartMapper.selectById(cartId);

        // 获取服务费和加价
        BigDecimal charge = getCharge(buyerCart.getGoodsId());
        BigDecimal addPrice = getAddPrice_new(buyerCart.getGoodsId());

        LambdaQueryWrapper<BuyerCartSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BuyerCartSku::getCartId, buyerCart.getCartId());
        List<BuyerCartSku> list = buyerCartSkuMapper.selectList(wrapper);
        BigDecimal totalPrice = BigDecimal.ZERO;
        BigDecimal totalOriginalPrice = BigDecimal.ZERO;
        BigDecimal totalSalerPrice = BigDecimal.ZERO;

        // 获取渠道商商品商城加价
        LambdaQueryWrapper<CompanySkuCharge> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(CompanySkuCharge::getCompanyId, TokenService.getUserBytoken().getCompanyId())
                .eq(CompanySkuCharge::getGoodsId, list.get(0).getGoodsId());
        List<CompanySkuCharge> chargeList = companySkuChargeMapper.selectList(wrapper3);
        Map<Integer, BigDecimal> chargeMap = null;
        if (chargeList.size() > 0) {
            chargeMap = chargeList.stream().collect(Collectors.toMap(CompanySkuCharge::getSkuInfoId,
                    CompanySkuCharge::getMallAddPrice));
        }

        String orderType = "SP";
        Integer goodsType = null;
        Integer vendorId = null;
        if (list.size() > 0) {
            GoodsInfo goodsInfo = goodsInfoMapper.selectById(list.get(0).getGoodsId());
            if (goodsInfo != null) {
                goodsType = goodsInfo.getGoodsType();
                vendorId = goodsInfo.getVendorId();
                // 1-电影，2-蛋糕，3-电子券，4-api电商，5-线下供应商
                if (2 == goodsInfo.getGoodsType()) {
                    orderType = "CAKE";
                } else if (3 == goodsInfo.getGoodsType()) {
                    orderType = "DZQ";
                }
            }
            BigDecimal Quantity;
            SkuInfo skuInfo;

            BigDecimal price;
            for (BuyerCartSku a : list) {
                Quantity = new BigDecimal(a.getSkuQuantity());
                skuInfo = skuInfoMapper.selectById(a.getSkuId());

                // 计算并记录价格
                price = skuInfo.getSkuPrice();
                // 原价
                a.setOriginalPrice(price);
                totalOriginalPrice = totalOriginalPrice.add(price);

                // 渠道商进货价
                price = price.multiply(BigDecimal.ONE.add(charge));
                a.setSalerPrice(price);
                totalSalerPrice = totalSalerPrice.add(price);

                BigDecimal addMallPrice = chargeMap == null ? BigDecimal.ZERO :
                        chargeMap.getOrDefault(skuInfo.getId(), BigDecimal.ZERO);
                // 顾客购买价
                if (skuInfo.getAdvocatePrice() != null) {
                    price = skuInfo.getAdvocatePrice();
                    log.info(goodsInfo.getGoodsName() + "-" + skuInfo.getSkuInfo() + ",建议售价不为空，取建议售价：" + skuInfo.getAdvocatePrice() + "元");
                    log.info(goodsInfo.getGoodsName() + "-" + skuInfo.getSkuInfo() + ",最终售价是：" +
                            "建议售价(" + skuInfo.getAdvocatePrice() + ")+商城加价(" + addMallPrice + ") +最终福利卡加价(" + addPrice + ")=" + price.add(addMallPrice).add(addPrice) + "元");
                }

                log.info(goodsInfo.getGoodsName() + "-" + skuInfo.getSkuInfo() + ",建议售价为空，取结算成本：" + skuInfo.getSkuPrice().multiply(BigDecimal.ONE.add(charge)) + "元");
                log.info(goodsInfo.getGoodsName() + "-" + skuInfo.getSkuInfo() + ",最终售价是：" +
                        "结算成本(" + skuInfo.getSkuPrice().multiply(BigDecimal.ONE.add(charge)) + ")+商城加价(" + addMallPrice + ") +最终福利卡加价(" + addPrice + ")=" + price.add(addMallPrice).add(addPrice) + "元");

                price = price.add(addMallPrice).add(addPrice);
                a.setSkuPrice(price);

                buyerCartSkuMapper.updateById(a);

                price = price.multiply(Quantity);
                totalPrice = totalPrice.add(price);

                // 更新库存
                skuInfo.setStock(skuInfo.getStock() - Quantity.intValue());
                skuInfoMapper.updateById(skuInfo);
            }
        }

        String orderId = IDGenerator.generate20("Order");

        // 复制一个订单地址出来
        BuyerAddress buyerAddress = iBuyerAddressService.getById(addressId);
        buyerAddress.setIsShow(0);
        buyerAddress.setIsDefault(0);
        buyerAddress.setOrderId(orderId);
        buyerAddress.setId(null);
        iBuyerAddressService.save(buyerAddress);
        LambdaQueryWrapper<BuyerAddress> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(BuyerAddress::getOrderId, orderId);
        buyerAddress = iBuyerAddressService.getBaseMapper().selectOne(wrapper1);

        BuyerOrder order = new BuyerOrder();
        order.setOrderId(orderId);
        order.setDistributorId(TokenService.getUserBytoken().getCompanyId());
        order.setVendorId(vendorId);
        order.setUserId(TokenService.getUserBytoken().getId());
        order.setCartId(cartId);
        order.setAddressId(buyerAddress.getId());
        order.setTotalPrice(totalPrice);
        order.setTotalOriginalPrice(totalOriginalPrice);
        order.setTotalSalerPrice(totalSalerPrice);
        order.setOrderStatus(1);
        order.setOrderType(orderType);
        order.setGoodsType(goodsType);
        int i = this.baseMapper.insert(order);
        if (i > 0) {
            // 隐藏购物车
            buyerCart.setCartStatus(1);
            buyerCartMapper.updateById(buyerCart);
            return new CheckOutVo(totalPrice, orderId);
        }
        return null;
    }

    /***
     * 获取购物车信息
     * */
    public CartOutVo getCartOutVo(Integer cartId) {
        CartOutVo cartOutVo = new CartOutVo();
        BuyerCart buyerCart = buyerCartMapper.selectById(cartId);
        BeanUtils.copyProperties(buyerCart, cartOutVo);

        // 拼接子项
        LambdaQueryWrapper<BuyerCartSku> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(BuyerCartSku::getCartId, buyerCart.getCartId());

        List<BuyerCartSku> cartSku = buyerCartSkuMapper.selectList(wrapper1);
        if (cartSku.size() == 0) {
            return null;
        }

        GoodsInfo goodsInfo = goodsInfoMapper.selectById(buyerCart.getGoodsId());
        cartOutVo.setGoodsName(goodsInfo.getGoodsName());

        List<SkuPo> skuPoList = cartSku.stream().map(
                e -> {
                    // 查询sku具体信息
                    SkuInfo skuInfo = skuInfoMapper.selectById(e.getSkuId());
                    GoodSku goodSku = goodSkuMapper.selectById(skuInfo.getSkuNameId());
                    // 填充子项信息
                    SkuPo po = new SkuPo();
                    po.setCartSkuId(e.getId());
                    po.setPicUrl(goodsInfo.getPicUrl());
                    // 订单生成时的价格
                    po.setGoodsPrice(e.getSkuPrice());
                    po.setDescription(goodSku.getSkuName() + " " + skuInfo.getSkuInfo());
                    po.setSkuId(skuInfo.getId());
                    po.setSkuNameId(skuInfo.getSkuNameId());
                    po.setSkuQuantity(e.getSkuQuantity());
                    return po;
                }
        ).collect(Collectors.toList());
        cartOutVo.setSkuPos(skuPoList);
        return cartOutVo;
    }

    @Override
    public IPage<OrderInfoOutVo> getList(Integer showType, Long pageNo, Long pageSize) {
        // 取消订单
        checkOrderUnpaid(false);

        LambdaQueryWrapper<BuyerOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(showType != null, BuyerOrder::getOrderStatus, showType);
        wrapper.ne(BuyerOrder::getOrderType, "DY");
        wrapper.eq(BuyerOrder::getUserId, TokenService.getUserBytoken().getId());
        wrapper.orderByDesc(BuyerOrder::getCreateTime);

        Page<BuyerOrder> page = new Page<>(pageNo, pageSize);
        IPage<BuyerOrder> iPage = this.baseMapper.selectPage(page, wrapper);
        IPage<OrderInfoOutVo> convert = iPage.convert(BuyerOrder -> {
            OrderInfoOutVo form = new OrderInfoOutVo();
            BeanUtils.copyProperties(BuyerOrder, form);
            if (BuyerOrder.getCartId() != null) {
                form.setCartOutVo(getCartOutVo(BuyerOrder.getCartId()));
            }
            form.setOrderId(BuyerOrder.getOrderId());
            form.setPayPrice(BuyerOrder.getTotalPrice());
            form.setTotleYF(BigDecimal.ZERO);
            return form;
        });

        return convert;
    }

    @Override
    public String flkpay(FlkPayInVo inVo) throws IOException {
        // 1. 校验订单状态
        BuyerOrder buyerOrder = this.getById(inVo.getOrderId());
        if (buyerOrder == null) {
            return "找不到订单信息！";
        }
        if (buyerOrder.getOrderStatus() != 1) {
            return "该订单已完成支付！";
        }

        // 2. 校验支付金额
        BigDecimal orderPrice = buyerOrder.getTotalPrice();
        if (orderPrice.compareTo(inVo.getPayPrice()) != 0) {
            return "请检查金额！";
        }

        // 3. 校验福利卡信息
        LambdaQueryWrapper<CardsInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CardsInfo::getId, inVo.getCardId());
        List<CardsInfo> cardsInfos = iCardsInfoService.getBaseMapper().selectList(wrapper);

        if (cardsInfos.size() != inVo.getCardId().size()) {
            return "找不到福利卡信息！";
        }

        for (CardsInfo a : cardsInfos) {
            LambdaQueryWrapper<CardsBatch2> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(CardsBatch2::getSecondBantchNum, a.getSecondBantchNum());
            CardsBatch2 batch2 = iCardsBatch2Service.getBaseMapper().selectOne(wrapper1);
            if (batch2 != null && batch2.getIsEnable() == 0) {
                return "福利卡已被冻结！";
            }
        }

        cardsInfos.forEach(c -> log.info("卡片信息：{}", c.toString()));
        // 根据价格升序
        Collections.sort(cardsInfos, Comparator.comparing(CardsInfo::getBalance));
        cardsInfos.forEach(c -> log.info("卡片信息：{}", c.toString()));

        // 4.多张福利卡支付
        BigDecimal needPayPrice = inVo.getPayPrice();
        BigDecimal cardPrice = BigDecimal.ZERO;
        String cardIds = "";
        Integer orderStatus = 1;
        String payMethod = "1";
        String rts = "success";
        for (CardsInfo cardsInfo : cardsInfos) {
            if (cardsInfo.getIsUsed() == 1) {
                return "该福利卡已使用，无法重复使用！";
            }

            // 4.1 判断是否扣完钱了
            if (needPayPrice.compareTo(BigDecimal.ZERO) == 0) {
                break;
            }

            // 4.2 循环支付
            log.info("订单剩余支付金额：{}", needPayPrice);
            cardPrice = cardsInfo.getBalance();
            if (cardPrice.compareTo(inVo.getPayPrice()) < 0) {
                // 记录卡片
                cardIds = StringUtils.hasLength(cardIds) ? "," + cardIds + cardsInfo.getId() :
                        cardsInfo.getId().toString();
                // 4.3 卡片余额不足支付,扣减当前卡片余额
                log.info("卡片余额不足支付,扣减当前卡片余额：" + cardPrice);
                needPayPrice = needPayPrice.subtract(cardPrice);
                cardsInfo.setBalance(BigDecimal.ZERO);
                if (!cardsInfo.getCardType().equals("JFK")) {
                    cardsInfo.setIsUsed(1);
                }
                iCardsInfoService.updateById(cardsInfo);

                // 4.4 记录福利卡扣减金额
                OrderCard orderCard = new OrderCard();
                orderCard.setOrderId(inVo.getOrderId());
                orderCard.setCardId(cardsInfo.getId());
                orderCard.setPayAmount(cardPrice);
                orderCard.setDeleted(0);
                iOrderCardService.getBaseMapper().insert(orderCard);
            } else {
                // 记录卡片
                cardIds = StringUtils.hasLength(cardIds) ? "," + cardIds + cardsInfo.getId() :
                        cardsInfo.getId().toString();
                // 4.4 卡片余额充足，扣减当前卡片余额
                cardPrice = cardPrice.subtract(needPayPrice);
                log.info("卡片余额充足，当前卡片余额：" + cardsInfo.getBalance() + "，扣减后余额：" + cardPrice);
                cardsInfo.setBalance(cardPrice);
                if (!cardsInfo.getCardType().equals("JFK")) {
                    cardsInfo.setIsUsed(1);
                }
                iCardsInfoService.updateById(cardsInfo);

                // 4.4 记录福利卡扣减金额
                OrderCard orderCard = new OrderCard();
                orderCard.setOrderId(inVo.getOrderId());
                orderCard.setCardId(cardsInfo.getId());
                orderCard.setPayAmount(needPayPrice);
                orderCard.setDeleted(0);
                iOrderCardService.getBaseMapper().insert(orderCard);

                needPayPrice = BigDecimal.ZERO;
                orderStatus = 2;
                break;
            }

        }

        if (needPayPrice.compareTo(BigDecimal.ZERO) > 0) {
            payMethod = "3";
            rts = rts + "," + needPayPrice;
            log.info("福利卡扣减完毕，还需要现金支付：" + needPayPrice + "元");
            orderStatus = 5;
        }

        // 5.更新订单状态
        buyerOrder.setOrderStatus(orderStatus);
        buyerOrder.setCardId(cardIds);
        // 更新福利卡支付金额
        buyerOrder.setCardPrice(inVo.getPayPrice().subtract(needPayPrice));
        // 更新现金应付金额
        buyerOrder.setPayablePrice(needPayPrice);
        // 支付方式  1-福利卡支付 2-微信支付 3-混合支付
        buyerOrder.setPayMethod(payMethod);
        buyerOrder.setPayTime(LocalDateTime.now());

        this.updateById(buyerOrder);

        return rts;
    }

    private BigDecimal getCharge(Integer goodsId) {
        // 获取服务费
        LambdaQueryWrapper<CompanyGoods> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(CompanyGoods::getCompanyId, TokenService.getUserBytoken().getCompanyId());
        wrapper1.eq(CompanyGoods::getGoodsId, goodsId);
        List<CompanyGoods> companyGoodsList = iCompanyGoodsService.list(wrapper1);
        BigDecimal charge = BigDecimal.ZERO;
        if (companyGoodsList.size() > 0 && StringUtils.hasLength(companyGoodsList.get(0).getCustomCharge())) {
            charge = new BigDecimal(companyGoodsList.get(0).getCustomCharge()).divide(new BigDecimal(100));
        }
        return charge;
    }

    private BigDecimal getAddPrice(Integer goodsId) {
        BigDecimal addPrice = BigDecimal.ZERO;
        // 获取加价
        BenefitCardOutVo cardsInfo = iCardsInfoService.getInUseCard();
        if (cardsInfo == null) {
            return addPrice;
        }
        CardsInfo cardsInfo1 = iCardsInfoService.getById(cardsInfo.getId());
        String batch2Num = cardsInfo1.getSecondBantchNum();
        LambdaQueryWrapper<BatchGoods> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(BatchGoods::getSecondBantchNum, batch2Num);
        wrapper2.eq(BatchGoods::getGoodsId, goodsId);
        List<BatchGoods> batchGoods = iBatchGoodsService.list(wrapper2);
        if (batchGoods.size() > 0) {
            addPrice = batchGoods.get(0).getAddPrice();
        }
        return addPrice;
    }

    private BigDecimal getAddPrice_new(Integer goodsId) {
        // 获取最高加价
        BigDecimal addPrice = BigDecimal.ZERO;

        QueryWrapper<BatchGoods> wrapper2 = new QueryWrapper<>();
        wrapper2.inSql("second_bantch_num",
                "select second_bantch_num from benefit_cards_info where is_enable = 0 and user_id = '"
                        + TokenService.getUserBytoken().getId() + "'");
        wrapper2.eq("goods_id", goodsId);
        List<BatchGoods> batchGoods = goodsInfoMapper.getGoodsMaxPrice(wrapper2);
        batchGoods.remove(null);
        if (!batchGoods.isEmpty()) {
            for (BatchGoods batchGood : batchGoods) {
                System.out.println(batchGood.getAddPrice());
            }
            System.out.println(batchGoods);
            addPrice = batchGoods.get(0).getAddPrice();
        }
        log.info("商品id：" + goodsId + "，加价：" + addPrice);
        return addPrice;
    }

    @Override
    public IPage<VenderOrdersOutVo> getOrderList(VenderOrdersInVo inVo, Long pageNo, Long pageSize) {
        QueryWrapper<VenderOrdersOutVo> wrapper = new QueryWrapper<>();
        wrapper.eq("d.vendor_id", TokenService.getUserBytoken().getCompanyId());
        // 查询条件
        wrapper.like(StringUtils.hasLength(inVo.getOrderNo()), "a.order_id", inVo.getOrderNo());
        wrapper.like(StringUtils.hasLength(inVo.getVenderOrderNo()), "a.order_id", inVo.getVenderOrderNo());
        wrapper.like(StringUtils.hasLength(inVo.getGoodsName()), "d.goods_name", inVo.getGoodsName());
        wrapper.like(StringUtils.hasLength(inVo.getName()), "b.name", inVo.getName());
        wrapper.like(StringUtils.hasLength(inVo.getMobile()), "b.mobile", inVo.getMobile());
        wrapper.eq((inVo.getOrderStatus() != null), "a.order_status", inVo.getOrderStatus());
        wrapper.ge((inVo.getMinTotlePrice() != null), "CAST((c.sku_quantity * c.sku_price) AS DECIMAL(9, 2))",
                inVo.getMinTotlePrice());
        wrapper.le((inVo.getMaxTotlePrice() != null), "CAST((c.sku_quantity * c.sku_price) AS DECIMAL(9, 2))",
                inVo.getMaxTotlePrice());
        wrapper.ge(StrUtil.isNotEmpty(inVo.getStartTime()), "a.pay_time", inVo.getStartTime());
        wrapper.le(StrUtil.isNotEmpty(inVo.getEndTime()), "a.pay_time", inVo.getEndTime());

        Page<VenderOrdersOutVo> page = new Page<>(pageNo, pageSize);
        IPage<VenderOrdersOutVo> iPage = this.baseMapper.getListPageByConditions(page, wrapper);
        return iPage;
    }

    @Override
    public String delivery(DeliveryInVo inVo) {
        BuyerOrder order = this.getBaseMapper().selectById(inVo.getOrderId());
        if (order == null) {
            return "未找到该订单！";
        }
        if (order.getOrderStatus() != 2) {
            return "订单不属于待发货状态！";
        }

        order.setOrderStatus(3);
        order.setExpressNo(inVo.getExpressNo());
        order.setExpressTime(LocalDateTime.now());
        this.getBaseMapper().updateById(order);
        return "success";
    }

    @Override
    public IPage<VenderOrdersOutVo> getSalerOrderList(VenderOrdersInVo inVo, Long pageNo, Long pageSize) {
        QueryWrapper<VenderOrdersOutVo> wrapper = new QueryWrapper<>();
        wrapper.eq("a.distributor_id", TokenService.getUserBytoken().getCompanyId());
        // 查询条件
        wrapper.eq(inVo.getGoodsType() != null, "a.goods_type", inVo.getGoodsType());
        wrapper.like(StringUtils.hasLength(inVo.getOrderNo()), "a.order_id", inVo.getOrderNo());
        wrapper.like(StringUtils.hasLength(inVo.getVenderOrderNo()), "a.order_id", inVo.getVenderOrderNo());
        wrapper.like(StringUtils.hasLength(inVo.getGoodsName()), "d.goods_name", inVo.getGoodsName());
        wrapper.like(StringUtils.hasLength(inVo.getName()), "b.name", inVo.getName());
        wrapper.like(StringUtils.hasLength(inVo.getMobile()), "b.mobile", inVo.getMobile());
        wrapper.eq((inVo.getOrderStatus() != null), "a.order_status", inVo.getOrderStatus());
        wrapper.ge((inVo.getMinTotlePrice() != null), "CAST((c.sku_quantity * c.sku_price) AS DECIMAL(9, 2))",
                inVo.getMinTotlePrice());
        wrapper.le((inVo.getMaxTotlePrice() != null), "CAST((c.sku_quantity * c.sku_price) AS DECIMAL(9, 2))",
                inVo.getMaxTotlePrice());
        wrapper.ge(StrUtil.isNotEmpty(inVo.getStartTime()), "a.pay_time", inVo.getStartTime());
        wrapper.le(StrUtil.isNotEmpty(inVo.getEndTime()), "a.pay_time", inVo.getEndTime());

        wrapper.ne("a.order_type", "DY");

        Page<VenderOrdersOutVo> page = new Page<>(pageNo, pageSize);
        IPage<VenderOrdersOutVo> iPage = this.baseMapper.getListPageByConditions(page, wrapper);
        List<VenderOrdersOutVo> outVoList = iPage.getRecords();
        for (VenderOrdersOutVo venderOrdersOutVo : outVoList) {
            String cardType = "";
            String salePrice = "";
            if (venderOrdersOutVo != null && StrUtil.isNotBlank(venderOrdersOutVo.getOrderNo())) {
                String orderNo = venderOrdersOutVo.getOrderNo();
                BigDecimal result = BigDecimal.ZERO;
                // 循环得到每个订单积分卡的实际售价
                List<OrderCard> list =
                        iOrderCardService.list(Wrappers.<OrderCard>lambdaQuery().eq(OrderCard::getOrderId, orderNo));
                for (OrderCard orderCard : list) {
                    // 获取已使用的积分
                    BigDecimal payAmount = orderCard.getPayAmount();
                    // 获取卡面额和卡售价
                    CardsInfo cardsInfo = iCardsInfoService.getById(orderCard.getCardId());
                    cardType = cardsInfo.getCardType();
                    // 获取卡面额和卡售价
                    String secondBantchNum = cardsInfo.getSecondBantchNum();
                    CardsBatch2 cardsBatch2 = iCardsBatch2Service.getOne(Wrappers.<CardsBatch2>lambdaQuery()
                            .eq(CardsBatch2::getSecondBantchNum, secondBantchNum));
                    // 获取卡的售价
                    salePrice = cardsBatch2.getSalePrice();
                    // 获取卡面值
                    String faceValue = cardsBatch2.getFaceValue();
                    // 获取商品利润额
                    result = divideAndMultiply(salePrice, faceValue, payAmount).add(result);
                }
                BuyerOrder buyerOrder = buyerOrderMapper.selectById(orderNo);
                assert buyerOrder != null;
                BigDecimal payablePrice = BigDecimal.ZERO;
                if (buyerOrder.getPayablePrice() != null) {
                    payablePrice = buyerOrder.getPayablePrice();
                }
                BigDecimal salePriceDecimal = payablePrice.add(result);
                // 1. 渠道商售价
                venderOrdersOutVo.setPrice(salePriceDecimal);
                // 2. 渠道商成本
                BigDecimal cost = buyerOrder.getTotalSalerPrice();
                venderOrdersOutVo.setCost(buyerOrder.getTotalSalerPrice());
                buyerOrder.setCost(cost);
                // 3. 渠道商利润
                if (cardType.equals("JFK")) {
                    venderOrdersOutVo.setMargin(salePriceDecimal.subtract(cost));
                    buyerOrder.setMargin(venderOrdersOutVo.getMargin());
                }
                if (cardType.equals("LPK")) {
                    // 单张售价
                    BigDecimal dj = BigDecimal.valueOf(Long.parseLong(salePrice));
                    // 获取服务费
                    String charge = venderOrdersOutVo.getCharge();
                    if (!StrUtil.isNotEmpty(charge)) {
                        charge = String.valueOf(0);
                    }
                    // 获取供应价
                    BigDecimal margin = dj.subtract(new BigDecimal(charge).add(venderOrdersOutVo.getSupplyPrice()));
                    venderOrdersOutVo.setMargin(margin);
                    buyerOrder.setMargin(margin);
                }
                buyerOrderMapper.updateById(buyerOrder);
                // 4. 渠道商利润率
                Assert.notNull(venderOrdersOutVo.getCost(), "成本不能为空！");
                Assert.isTrue(!Objects.equals(venderOrdersOutVo.getCost(), BigDecimal.ZERO), "成本不能为空！");
                BigDecimal divide = venderOrdersOutVo.getMargin().divide(venderOrdersOutVo.getCost(), 2,
                        RoundingMode.UP).multiply(BigDecimal.valueOf(100));
                venderOrdersOutVo.setProfitMargin(divide);
            }
        }

        // 判断是否有工单
        for (VenderOrdersOutVo record : iPage.getRecords()) {
            String orderNo = record.getOrderNo();
            WorkOrderInfo workOrderInfo = iWorkOrderInfoService.getOne(Wrappers.<WorkOrderInfo>lambdaQuery()
                    .eq(WorkOrderInfo::getOrderNo, orderNo));
            if (workOrderInfo != null) {
                record.setHasWorkOrder(1);
                record.setWorkOrderId(workOrderInfo.getId());
            } else {
                record.setHasWorkOrder(0);
            }
        }
        return iPage;
    }

    private BigDecimal divideAndMultiply(String salePrice, String faceValue, BigDecimal payAmount) {
        BigDecimal number1 = BigDecimal.valueOf(Double.parseDouble(salePrice));
        BigDecimal number2 = BigDecimal.valueOf(Double.parseDouble(faceValue));
        Assert.notNull(number2, "面额不能为空！");
        Assert.isTrue(number1.compareTo(BigDecimal.valueOf(0)) > 0, "售价不能为负数");
        Assert.isTrue(number2.compareTo(BigDecimal.valueOf(0)) > 0, "面额不能为负数");
        BigDecimal divisionResult = number1.divide(number2, 2, RoundingMode.UP);
        return divisionResult.multiply(payAmount);
    }

    @Override
    public OrderIdsOutVo getUserOrderIds(String userId) {
        OrderIdsOutVo outVo = new OrderIdsOutVo();

        LambdaQueryWrapper<BuyerOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BuyerOrder::getUserId, userId);
        List<BuyerOrder> list = this.getBaseMapper().selectList(wrapper);

        if (list.size() > 0) {
            outVo.setOrderIds(list.stream().map(BuyerOrder::getOrderId).collect(Collectors.toList()));
        }

        return outVo;
    }

    @Override
    public UserOrderInfoOutVo getUserOrderInfo(String orderId) {
        UserOrderInfoOutVo outVo = new UserOrderInfoOutVo();
        BuyerOrder order = this.baseMapper.selectById(orderId);
        if (order == null) {
            return outVo;
        }

        LambdaQueryWrapper<BuyerCartSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BuyerCartSku::getCartId, order.getCartId());

        List<BuyerCartSku> cartSkuList = buyerCartSkuMapper.selectList(wrapper);
        if (cartSkuList.size() == 0) {
            return outVo;
        }

        // 设置sku信息
        List<String> goodsSkus = cartSkuList.stream()
                .map(a -> a.getSkuName() + "-" + a.getSkuInfo())
                .collect(Collectors.toList());
        outVo.setGoodsSkus(goodsSkus);

        // 设置商品信息
        GoodsInfo goodsInfo = goodsInfoMapper.selectById(cartSkuList.get(0).getGoodsId());
        if (goodsInfo == null) {
            return outVo;
        }
        outVo.setGoodsId(goodsInfo.getId());

        outVo.setGoodsName(goodsInfo.getGoodsName());

        outVo.setVenderId(goodsInfo.getVendorId());

        CompanyInfo companyInfo = iCompanyInfoService.getById(goodsInfo.getVendorId());
        if (companyInfo == null) {
            return outVo;
        }
        outVo.setVenderName(companyInfo.getCompanyName());

        return outVo;
    }

    @Override
    public IPage<DYOrderOutVo> queryDYOrderList(Long pageNo, Long pageSize) {
        // 取消订单
        checkOrderUnpaid(false);

        LambdaQueryWrapper<BuyerOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BuyerOrder::getOrderType, "DY");
        wrapper.eq(BuyerOrder::getUserId, TokenService.getUserBytoken().getId());
        wrapper.orderByDesc(BuyerOrder::getCreateTime);

        Page<BuyerOrder> page = new Page<>(pageNo, pageSize);
        IPage<BuyerOrder> iPage = this.baseMapper.selectPage(page, wrapper);

        IPage<DYOrderOutVo> convert = iPage.convert(BuyerOrder -> {
            DYOrderOutVo form = new DYOrderOutVo();
            BeanUtils.copyProperties(BuyerOrder, form);
            return form;
        });

        return convert;
    }

    @Override
    public BuyerOrder saveOrder(String orderId) {
        //
        return null;
    }

    //3.1 支付成功，修改订单记录表状态：待发货，存储交易流水号
    @Override
    public void paySuccess(String outTradeNo, String transactionId) {
        //1 查询当前订单支付记录表状态是否是已经支付
        BuyerOrder paymentInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<BuyerOrder>()
                        .eq(BuyerOrder::getOrderId, outTradeNo)
        );
        Integer orderStatus = paymentInfo.getOrderStatus();
        if (orderStatus != 2) {
            //2 如果支付记录表支付状态没有支付，更新
            paymentInfo.setOrderStatus(2);
            paymentInfo.setTradeNo(transactionId);
            baseMapper.updateById(paymentInfo);
        }
    }

    @Override
    public SalerCwtjOutVo getSalerCwtj() {
        BigDecimal cakeTransactionAmount = BigDecimal.ZERO;
        BigDecimal couponTransactionAmount = BigDecimal.ZERO;
        BigDecimal mallTransactionAmount = BigDecimal.ZERO;
        BigDecimal movieTransactionAmount = BigDecimal.ZERO;
        //订单类型，CAKE-蛋糕 DZQ-电子券 SP-普通商品，DY-电影票
        // 查询蛋糕交易额
        LambdaQueryWrapper<BuyerOrder> cakeWrapper = new LambdaQueryWrapper<>();
        cakeWrapper.eq(BuyerOrder::getOrderType, "cake");
        List<BuyerOrder> cakeOrders = buyerOrderMapper.selectList(cakeWrapper);
        for (BuyerOrder order : cakeOrders) {
            if (order.getTotalOriginalPrice() != null) {
                cakeTransactionAmount = cakeTransactionAmount.add(order.getTotalOriginalPrice());
            }
        }
        // 查询电子券交易额
        LambdaQueryWrapper<BuyerOrder> couponWrapper = new LambdaQueryWrapper<>();
        couponWrapper.eq(BuyerOrder::getOrderType, "DZQ");
        List<BuyerOrder> couponOrders = buyerOrderMapper.selectList(couponWrapper);
        for (BuyerOrder order : couponOrders) {
            if (order.getTotalOriginalPrice() != null) {
                couponTransactionAmount = couponTransactionAmount.add(order.getTotalOriginalPrice());
            }
        }
        // 查询商城交易额
        LambdaQueryWrapper<BuyerOrder> mallWrapper = new LambdaQueryWrapper<>();
        mallWrapper.eq(BuyerOrder::getOrderType, "SP");
        List<BuyerOrder> mallOrders = buyerOrderMapper.selectList(mallWrapper);
        for (BuyerOrder order : mallOrders) {
            if (order.getTotalOriginalPrice() != null) {
                mallTransactionAmount = mallTransactionAmount.add(order.getTotalOriginalPrice());
            }
        }
        // 查询电影交易额
        LambdaQueryWrapper<BuyerOrder> movieWrapper = new LambdaQueryWrapper<>();
        movieWrapper.eq(BuyerOrder::getOrderType, "DY");
        List<BuyerOrder> movieOrders = buyerOrderMapper.selectList(movieWrapper);
        for (BuyerOrder order : movieOrders) {
            if (order.getTotalOriginalPrice() != null) {
                movieTransactionAmount = movieTransactionAmount.add(order.getTotalOriginalPrice());
            }
        }
        // 计算总交易额
        BigDecimal totalTransactionAmount = cakeTransactionAmount.add(couponTransactionAmount)
                .add(mallTransactionAmount).add(movieTransactionAmount);
        // 蛋糕毛利额
        BigDecimal cakeGrossProfit;
        BigDecimal cakeGrossProfitRate = BigDecimal.valueOf(0.10);
        cakeGrossProfit = cakeGrossProfitRate.multiply(cakeTransactionAmount);
        //商场毛利额
        BigDecimal mallGrossProfit;
        BigDecimal mallGrossProfitRate = BigDecimal.valueOf(0.10);
        mallGrossProfit = mallGrossProfitRate.multiply(mallTransactionAmount);

        BigDecimal couponGrossProfit;
        BigDecimal couponGrossProfitRate = BigDecimal.valueOf(0.10);
        couponGrossProfit = couponGrossProfitRate.multiply(couponTransactionAmount);

        BigDecimal movieGrossProfit;
        BigDecimal movieGrossProfitRate = BigDecimal.valueOf(0.1);
        movieGrossProfit = movieGrossProfitRate.multiply(movieTransactionAmount);

        BigDecimal totalGrossProfit;
        BigDecimal totalGrossProfitRate = BigDecimal.valueOf(0.1);
        totalGrossProfit = totalGrossProfitRate.multiply(movieTransactionAmount);

        SalerCwtjOutVo cwtjOutVo = new SalerCwtjOutVo();
        cwtjOutVo.setTotalTransactionAmount(totalTransactionAmount);
        cwtjOutVo.setTotalGrossProfitRate(totalGrossProfitRate);
        cwtjOutVo.setTotalGrossProfit(totalGrossProfit);
        cwtjOutVo.setCakeTransactionAmount(cakeTransactionAmount);
        cwtjOutVo.setCakeGrossProfitRate(cakeGrossProfitRate);
        cwtjOutVo.setCakeGrossProfit(cakeGrossProfit);
        cwtjOutVo.setCouponTransactionAmount(couponTransactionAmount);
        cwtjOutVo.setCouponGrossProfitRate(couponGrossProfitRate);
        cwtjOutVo.setCouponGrossProfit(couponGrossProfit);
        cwtjOutVo.setMallTransactionAmount(mallTransactionAmount);
        cwtjOutVo.setMallGrossProfitRate(mallGrossProfitRate);
        cwtjOutVo.setMallGrossProfit(mallGrossProfit);
        cwtjOutVo.setMovieTransactionAmount(movieTransactionAmount);
        cwtjOutVo.setMovieGrossProfitRate(movieGrossProfitRate);
        cwtjOutVo.setMovieGrossProfit(movieGrossProfit);
        // 订单类型要为0（已完成）
        return cwtjOutVo;
    }

    @Override
    public boolean checkVenderOrderStatus(Integer id) {

        QueryWrapper<VenderOrdersOutVo> wrapper = new QueryWrapper<>();
        wrapper.eq("d.vendor_id", id);
        wrapper.eq("a.order_status", 2);

        Page<VenderOrdersOutVo> page = new Page<>(1, 1);
        IPage<VenderOrdersOutVo> iPage = this.baseMapper.getListPageByConditions(page, wrapper);
        if (iPage.getTotal() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public IPage<VenderOrdersOutVo> getSysOrderList(VenderOrdersInVo inVo, Long pageNo, Long pageSize) {
        QueryWrapper<VenderOrdersOutVo> wrapper = new QueryWrapper<>();
        //wrapper.eq("d.vendor_id", TokenService.getUserBytoken().getCompanyId());
        // 查询条件
        wrapper.like(StringUtils.hasLength(inVo.getOrderNo()), "a.order_id", inVo.getOrderNo());
        wrapper.like(StringUtils.hasLength(inVo.getVenderOrderNo()), "a.order_id", inVo.getVenderOrderNo());
        wrapper.like(StringUtils.hasLength(inVo.getGoodsName()), "d.goods_name", inVo.getGoodsName());
        wrapper.like(StringUtils.hasLength(inVo.getName()), "b.name", inVo.getName());
        wrapper.like(StringUtils.hasLength(inVo.getMobile()), "b.mobile", inVo.getMobile());
        wrapper.eq((inVo.getOrderStatus() != null), "a.order_status", inVo.getOrderStatus());
        wrapper.ge((inVo.getMinTotlePrice() != null), "CAST((c.sku_quantity * c.sku_price) AS DECIMAL(9, 2))",
                inVo.getMinTotlePrice());
        wrapper.le((inVo.getMaxTotlePrice() != null), "CAST((c.sku_quantity * c.sku_price) AS DECIMAL(9, 2))",
                inVo.getMaxTotlePrice());
        wrapper.ge(StrUtil.isNotEmpty(inVo.getStartTime()), "a.pay_time", inVo.getStartTime());
        wrapper.le(StrUtil.isNotEmpty(inVo.getEndTime()), "a.pay_time", inVo.getEndTime());
        wrapper.ne("a.order_type", "DY");

        Page<VenderOrdersOutVo> page = new Page<>(pageNo, pageSize);
        IPage<VenderOrdersOutVo> iPage = this.baseMapper.getListPageByConditions(page, wrapper);
        return iPage;
    }

    @Override
    public List<Map<String, Object>> getLine() {
        Integer companyId = TokenService.getUserBytoken().getCompanyId();
        return this.baseMapper.getLineByVender(companyId);
    }

    @Override
    public String paySuccess(Map<String, String> resultMap) {
        // 提取参数
        String tradeState = resultMap.get("trade_state");
        String tradeStateDesc = resultMap.get("trade_state_desc");
        String outTradeNo = resultMap.get("out_trade_no");
        String transactionId = resultMap.get("transaction_id");

        // 查询订单信息
        BuyerOrder paymentInfo = baseMapper.selectOne(Wrappers.<BuyerOrder>lambdaQuery().eq(BuyerOrder::getOrderId,
                outTradeNo));

        // 判断微信支付系统返回的状态
        switch (tradeState) {
            case "SUCCESS":
                handleSuccessPayment(paymentInfo, tradeStateDesc);
                break;
            case "NOTPAY":
            case "REVOKED":
            case "PAYERROR":
                paymentInfo.setOrderStatus(PaymentStatus.PAID.getCode());
                break;
            case "USERPAYING":
                paymentInfo.setOrderStatus(PaymentStatus.UNPAID.getCode());
                break;
            default:
                // TODO:默认处理
                break;
        }
        paymentInfo.setTradeNo(transactionId);
        paymentInfo.setUpdatedTime(LocalDateTime.now());
        // 更新订单信息
        baseMapper.updateById(paymentInfo);

        return tradeState;
    }

    @Override
    public String refund(BuyerOrder buyerOrder) {
        // 1.恢复卡券余额
        // 1.1 根据订单id查询订单卡券表，找到每个卡券
        String orderId = buyerOrder.getOrderId();
        List<OrderCard> orderCardList =
                iOrderCardService.list(Wrappers.<OrderCard>lambdaQuery().eq(OrderCard::getOrderId, orderId));
        if (orderCardList.size() == 0) {
            return "订单或卡券不存在！";
        }
        for (OrderCard orderCard : orderCardList) {
            BigDecimal payAmount = orderCard.getPayAmount();
            Integer cardId = orderCard.getCardId();
            if (cardId == null || cardId == 0 || orderCard.getPayAmount() == null) {
                return "订单卡券存在异常";
            }
            // 到卡券信息表，把扣除余额返还
            CardsInfo cardsInfo = iCardsInfoService.getById(cardId);
            if (cardsInfo != null && cardsInfo.getBalance() != null) {
                cardsInfo.setBalance(cardsInfo.getBalance().add(payAmount));
                // 若是电影券，返还完余额后，设置成未使用
                if (cardsInfo.getCardType().equals("DYQ")) {
                    cardsInfo.setIsUsed(0);
                }
                iCardsInfoService.updateById(cardsInfo);
            }
        }
        // 修改订单状态
        buyerOrder.setOrderStatus(7);
        buyerOrder.setEndTime(LocalDateTime.now());
        // 商品货品数量增加
        increaseProductStock(buyerOrder);
        this.buyerOrderMapper.updateById(buyerOrder);
        return "SUCCESS";
    }

    @Override
    public void checkOrderUnpaid(boolean isJob) {
        // 查询所有未支付的订单
        LambdaQueryWrapper<BuyerOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BuyerOrder::getOrderStatus, 1);
        if (!isJob) {
            // 用户访问订单中心，主动触发
            wrapper.eq(BuyerOrder::getUserId, TokenService.getUserBytoken().getId());
        }
        List<BuyerOrder> orderList = this.getBaseMapper().selectList(wrapper);

        // 遍历订单列表
        for (BuyerOrder order : orderList) {
            if (isJob) {
                // 定时任务，10分钟后自动取消订单
                LocalDateTime add = order.getCreateTime();
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime expired = add.plusMinutes(10);
                if (expired.isAfter(now)) {
                    continue;
                }
            }

            // 设置订单已取消状态
            order.setOrderStatus(4);
            order.setEndTime(LocalDateTime.now());
            UpdateWrapper<BuyerOrder> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("order_id", order.getOrderId()).set("order_status", 4);
            this.getBaseMapper().update(null, updateWrapper);

            log.info("订单 ID=" + order.getOrderId() + " 已经超期自动取消订单");

            // 商品货品数量增加
            increaseProductStock(order);

        }
    }

    @Override
    public void increaseProductStock(BuyerOrder buyerOrder) {
        BuyerCart buyerCart = buyerCartMapper.selectById(buyerOrder.getCartId());
        LambdaQueryWrapper<BuyerCartSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BuyerCartSku::getCartId, buyerCart.getCartId());
        List<BuyerCartSku> cartSkuList = buyerCartSkuMapper.selectList(wrapper);
        cartSkuList.remove(null);
        if (cartSkuList != null && !cartSkuList.isEmpty() && cartSkuList.size() > 0) {
            cartSkuList.forEach(a -> {
                SkuInfo skuInfo = skuInfoMapper.selectById(a.getSkuId());
                skuInfo.setStock(skuInfo.getStock() + a.getSkuQuantity());
                skuInfoMapper.updateById(skuInfo);
            });
        }
    }

    @Override
    public String refundSuccess(Map<String, Object> result) {
        // 1. 提取参数

        String orderNo = (String) result.get("orderNo");
        String body = (String) result.get("body");
        HashMap<String,Object> map = JSONObject.parseObject(body, HashMap.class);
        BuyerOrder order = buyerOrderMapper.selectById(orderNo);

        // 判断微信支付系统返回的状态
        switch ( map.get("status").toString()) {
            case "SUCCESS":
                order.setOrderStatus(7);
                break;
            case "PROCESSING":
                order.setOrderStatus(9);
            default:
                // TODO:默认处理
                order.setOrderStatus(8);
                break;
        }
        order.setUpdatedTime(LocalDateTime.now());
        // 更新订单信息
        buyerOrderMapper.updateById(order);
        return  map.get("status").toString();
    }

    @Override
    public IPage<OrdersDyOutVo> getSalerOrderList_dy(OrdersDyInVo inVo, Long pageNo, Long pageSize) {
        QueryWrapper<OrdersDyOutVo> wrapper = new QueryWrapper<>();
        wrapper.eq("a.distributor_id", TokenService.getUserBytoken().getCompanyId());
        // 查询条件
        wrapper.like(StringUtils.hasLength(inVo.getOrderNo()), "a.order_id", inVo.getOrderNo());
        wrapper.eq((inVo.getOrderStatus() != null), "a.order_status", inVo.getOrderStatus());
        wrapper.like(StringUtils.hasLength(inVo.getVenderOrderNo()), "a.order_id", inVo.getVenderOrderNo());
        wrapper.like(StringUtils.hasLength(inVo.getPhone()), "b.phone", inVo.getPhone());
        wrapper.like(StringUtils.hasLength(inVo.getFlimName()), "a.flim_info", inVo.getFlimName());
        wrapper.ge((inVo.getMinTotlePrice() != null), "a.total_saler_price",
                inVo.getMinTotlePrice());
        wrapper.le((inVo.getMaxTotlePrice() != null), "a.total_saler_price",
                inVo.getMaxTotlePrice());
        wrapper.ge(StrUtil.isNotEmpty(inVo.getStartTime()), "a.pay_time", inVo.getStartTime());
        wrapper.le(StrUtil.isNotEmpty(inVo.getEndTime()), "a.pay_time", inVo.getEndTime());
        wrapper.eq("a.order_type", "DY");

        Page<OrdersDyOutVo> page = new Page<>(pageNo, pageSize);
        IPage<OrdersDyOutVo> iPage = this.baseMapper.getListPageByConditions_dy(page, wrapper);
        List<OrdersDyOutVo> outVoList = iPage.getRecords();
        for (OrdersDyOutVo venderOrdersOutVo : outVoList) {
            String salePrice = "";
            if (venderOrdersOutVo != null && StrUtil.isNotBlank(venderOrdersOutVo.getOrderNo())) {
                String orderNo = venderOrdersOutVo.getOrderNo();
                BigDecimal result = BigDecimal.ZERO;
                // 循环得到每个订单积分卡的实际售价
                List<OrderCard> list =
                        iOrderCardService.list(Wrappers.<OrderCard>lambdaQuery().eq(OrderCard::getOrderId, orderNo));
                if (list.size()>0){
                    for (OrderCard orderCard : list) {
                        // 获取已使用的积分
                        BigDecimal payAmount = orderCard.getPayAmount();
                        // 获取卡面额和卡售价
                        CardsInfo cardsInfo = iCardsInfoService.getById(orderCard.getCardId());
                        // 获取卡面额和卡售价
                        String secondBantchNum = cardsInfo.getSecondBantchNum();
                        CardsBatch2 cardsBatch2 = iCardsBatch2Service.getOne(Wrappers.<CardsBatch2>lambdaQuery()
                                .eq(CardsBatch2::getSecondBantchNum, secondBantchNum));
                        // 获取卡的售价
                        salePrice = cardsBatch2.getSalePrice();
                        // 获取卡面值
                        String faceValue = cardsBatch2.getFaceValue();
                        // 获取商品实际售价
                        result = divideAndMultiply(salePrice, faceValue, payAmount).add(result);
                    }
                }
                BuyerOrder buyerOrder = buyerOrderMapper.selectById(orderNo);
                if (buyerOrder != null){
                    BigDecimal payablePrice = BigDecimal.ZERO;
                    if (buyerOrder.getPayablePrice()!=null) {
                        payablePrice = buyerOrder.getPayablePrice();
                    }
                    BigDecimal salePriceDecimal = payablePrice.add(result);
                    // 1. 售价
                    venderOrdersOutVo.setPrice(salePriceDecimal);
                    // 2. 电影利润
                    BigDecimal cost = buyerOrder.getTotalSalerPrice();
                    venderOrdersOutVo.setMargin(salePriceDecimal.subtract(cost));
                    buyerOrder.setMargin(venderOrdersOutVo.getMargin());
                    // 3. 电影利润率 = sum（商品利润额）/sum（商品成本费）
                    BigDecimal profitMargin = venderOrdersOutVo.getMargin().divide(cost, 2, RoundingMode.UP).multiply(BigDecimal.valueOf(100));
                    venderOrdersOutVo.setProfitMargin(profitMargin);
                }
            }
        }
        for (OrdersDyOutVo record : iPage.getRecords()) {
            // 判断是否有工单
            String orderNo = record.getOrderNo();
            WorkOrderInfo workOrderInfo = iWorkOrderInfoService.getOne(Wrappers.<WorkOrderInfo>lambdaQuery()
                    .eq(WorkOrderInfo::getOrderNo, orderNo));
            if (workOrderInfo != null) {
                record.setHasWorkOrder(1);
                record.setWorkOrderId(workOrderInfo.getId());
            } else {
                record.setHasWorkOrder(0);
            }

            if (StringUtils.hasLength(record.getFlimName())) {
                // 处理电影信息，以逗号分隔
                String[] a = record.getFlimName().split(",");
                record.setFlimName(a[0]);
                record.setQuantity(Integer.valueOf(a[a.length - 1]));
            }
        }
        return iPage;
    }

    @Override
    public IPage<VenderOrdersOutVo> getSalerOrderList_query(String cardNo, Long pageNo, Long pageSize) {
        QueryWrapper<OrdersDyOutVo> wrapper = new QueryWrapper<>();
        wrapper.eq("a.distributor_id", TokenService.getUserBytoken().getCompanyId());
        wrapper.ne("a.order_type", "DY");
        // 查询条件
        wrapper.like(StringUtils.hasLength(cardNo), "h.benefit_cards_num", cardNo);
        Page<VenderOrdersOutVo> page = new Page<>(pageNo, pageSize);
        IPage<VenderOrdersOutVo> iPage = this.baseMapper.getListPageByConditions_query(page, wrapper);
        List<VenderOrdersOutVo> outVoList = iPage.getRecords();
        for (VenderOrdersOutVo venderOrdersOutVo : outVoList) {
            String cardType = "";
            String salePrice = "";
            if (venderOrdersOutVo != null && StrUtil.isNotBlank(venderOrdersOutVo.getOrderNo())) {
                String orderNo = venderOrdersOutVo.getOrderNo();
                BigDecimal result = BigDecimal.ZERO;
                // 循环得到每个订单积分卡的实际售价
                List<OrderCard> list =
                        iOrderCardService.list(Wrappers.<OrderCard>lambdaQuery().eq(OrderCard::getOrderId, orderNo));
                for (OrderCard orderCard : list) {
                    // 获取已使用的积分
                    BigDecimal payAmount = orderCard.getPayAmount();
                    // 获取卡面额和卡售价
                    CardsInfo cardsInfo = iCardsInfoService.getById(orderCard.getCardId());
                    cardType = cardsInfo.getCardType();
                    // 获取卡面额和卡售价
                    String secondBantchNum = cardsInfo.getSecondBantchNum();
                    CardsBatch2 cardsBatch2 = iCardsBatch2Service.getOne(Wrappers.<CardsBatch2>lambdaQuery()
                            .eq(CardsBatch2::getSecondBantchNum, secondBantchNum));
                    // 获取卡的售价
                    salePrice = cardsBatch2.getSalePrice();
                    // 获取卡面值
                    String faceValue = cardsBatch2.getFaceValue();
                    // 获取商品利润额
                    result = divideAndMultiply(salePrice, faceValue, payAmount).add(result);
                }
                BuyerOrder buyerOrder = buyerOrderMapper.selectById(orderNo);
                assert buyerOrder != null;
                BigDecimal payablePrice = BigDecimal.ZERO;
                if (buyerOrder.getPayablePrice() != null) {
                    payablePrice = buyerOrder.getPayablePrice();
                }
                BigDecimal salePriceDecimal = payablePrice.add(result);
                // 1. 渠道商售价
                venderOrdersOutVo.setPrice(salePriceDecimal);
                // 2. 渠道商成本
                BigDecimal cost = buyerOrder.getTotalSalerPrice();
                venderOrdersOutVo.setCost(buyerOrder.getTotalSalerPrice());
                buyerOrder.setCost(cost);
                // 3. 渠道商利润
                if (cardType.equals("JFK")) {
                    venderOrdersOutVo.setMargin(salePriceDecimal.subtract(cost));
                    buyerOrder.setMargin(venderOrdersOutVo.getMargin());
                }
                if (cardType.equals("LPK")) {
                    // 单张售价
                    BigDecimal dj = BigDecimal.valueOf(Long.parseLong(salePrice));
                    // 获取服务费
                    String charge = venderOrdersOutVo.getCharge();
                    if (!StrUtil.isNotEmpty(charge)) {
                        charge = String.valueOf(0);
                    }
                    // 获取供应价
                    BigDecimal margin = dj.subtract(new BigDecimal(charge).add(venderOrdersOutVo.getSupplyPrice()));
                    venderOrdersOutVo.setMargin(margin);
                    buyerOrder.setMargin(margin);
                }
                buyerOrderMapper.updateById(buyerOrder);
                // 4. 渠道商利润率
                Assert.notNull(venderOrdersOutVo.getCost(), "成本不能为空！");
                Assert.isTrue(!Objects.equals(venderOrdersOutVo.getCost(), BigDecimal.ZERO), "成本不能为空！");
                BigDecimal divide = venderOrdersOutVo.getMargin().divide(venderOrdersOutVo.getCost(), 2,
                        RoundingMode.UP).multiply(BigDecimal.valueOf(100));
                venderOrdersOutVo.setProfitMargin(divide);
            }
        }

        // 判断是否有工单
        for (VenderOrdersOutVo record : iPage.getRecords()) {
            String orderNo = record.getOrderNo();
            WorkOrderInfo workOrderInfo = iWorkOrderInfoService.getOne(Wrappers.<WorkOrderInfo>lambdaQuery()
                    .eq(WorkOrderInfo::getOrderNo, orderNo));
            if (workOrderInfo != null) {
                record.setHasWorkOrder(1);
                record.setWorkOrderId(workOrderInfo.getId());
            } else {
                record.setHasWorkOrder(0);
            }
        }
        return iPage;
    }

    @Override
    public IPage<OrdersDyOutVo> getSalerOrderList_query_dy(String cardNo, Long pageNo, Long pageSize) {
        QueryWrapper<OrdersDyOutVo> wrapper = new QueryWrapper<>();
        wrapper.eq("a.distributor_id", TokenService.getUserBytoken().getCompanyId());
        // 查询条件
        wrapper.like(StringUtils.hasLength(cardNo), "d.benefit_cards_num", cardNo);
        wrapper.eq("a.order_type", "DY");

        Page<OrdersDyOutVo> page = new Page<>(pageNo, pageSize);
        IPage<OrdersDyOutVo> iPage = this.baseMapper.getListPageByConditions_query_dy(page, wrapper);
        List<OrdersDyOutVo> outVoList = iPage.getRecords();
        for (OrdersDyOutVo venderOrdersOutVo : outVoList) {
            String salePrice = "";
            if (venderOrdersOutVo != null && StrUtil.isNotBlank(venderOrdersOutVo.getOrderNo())) {
                String orderNo = venderOrdersOutVo.getOrderNo();
                BigDecimal result = BigDecimal.ZERO;
                // 循环得到每个订单积分卡的实际售价
                List<OrderCard> list =
                        iOrderCardService.list(Wrappers.<OrderCard>lambdaQuery().eq(OrderCard::getOrderId, orderNo));
                if (list.size() > 0){
                    for (OrderCard orderCard : list) {
                        // 获取已使用的积分
                        BigDecimal payAmount = orderCard.getPayAmount();
                        // 获取卡面额和卡售价
                        CardsInfo cardsInfo = iCardsInfoService.getById(orderCard.getCardId());
                        // 获取卡面额和卡售价
                        String secondBantchNum = cardsInfo.getSecondBantchNum();
                        CardsBatch2 cardsBatch2 = iCardsBatch2Service.getOne(Wrappers.<CardsBatch2>lambdaQuery()
                                .eq(CardsBatch2::getSecondBantchNum, secondBantchNum));
                        // 获取卡的售价
                        salePrice = cardsBatch2.getSalePrice();
                        // 获取卡面值
                        String faceValue = cardsBatch2.getFaceValue();
                        // 获取商品实际售价
                        result = divideAndMultiply(salePrice, faceValue, payAmount).add(result);
                    }
                }
                getByDY(orderNo,venderOrdersOutVo,result);
            }
        }
        for (OrdersDyOutVo record : iPage.getRecords()) {
            // 判断是否有工单
            String orderNo = record.getOrderNo();
            WorkOrderInfo workOrderInfo = iWorkOrderInfoService.getOne(Wrappers.<WorkOrderInfo>lambdaQuery()
                    .eq(WorkOrderInfo::getOrderNo, orderNo));
            if (workOrderInfo != null) {
                record.setHasWorkOrder(1);
                record.setWorkOrderId(workOrderInfo.getId());
            } else {
                record.setHasWorkOrder(0);
            }

            if (StringUtils.hasLength(record.getFlimName())) {
                // 处理电影信息，以逗号分隔
                String[] a = record.getFlimName().split(",");
                record.setFlimName(a[0]);
                record.setQuantity(Integer.valueOf(a[a.length - 1]));
            }
        }
        return iPage;
    }

    private void getByDY(String orderNo, OrdersDyOutVo venderOrdersOutVo, BigDecimal result) {
        BuyerOrder buyerOrder = buyerOrderMapper.selectById(orderNo);
        if (buyerOrder != null){
            BigDecimal payablePrice = BigDecimal.ZERO;
            if (buyerOrder.getPayablePrice()!=null) {
                payablePrice = buyerOrder.getPayablePrice();
            }
            BigDecimal salePriceDecimal = payablePrice.add(result);
            // 1. 售价
            venderOrdersOutVo.setPrice(salePriceDecimal);
            // 2. 电影利润
            BigDecimal cost = buyerOrder.getTotalSalerPrice();
            venderOrdersOutVo.setMargin(salePriceDecimal.subtract(cost));
            buyerOrder.setMargin(venderOrdersOutVo.getMargin());
            // 3. 电影利润率 = sum（商品利润额）/sum（商品成本费）
            BigDecimal profitMargin = venderOrdersOutVo.getMargin().divide(cost, 2, RoundingMode.UP).multiply(BigDecimal.valueOf(100));
            venderOrdersOutVo.setProfitMargin(profitMargin);
        }
    }

    private void handleSuccessPayment(BuyerOrder paymentInfo, String tradeStateDesc) {
        if (tradeStateDesc.contains("支付失败")) {
            paymentInfo.setOrderStatus(PaymentStatus.PAID.getCode());
        } else {
            paymentInfo.setOrderStatus(2);
        }
    }

    public FlimPayOutVo payFlim(String orderId) throws IOException {
        FlimPayOutVo outVo;

        String key = "order:ApplyKey:" + orderId;
        // 存入redis,15min失效
        String applyKey = redisTemplate.opsForValue().get(key).toString();
        key = "order:IsChangeSeats:" + orderId;
        String isChangeSeats = redisTemplate.opsForValue().get(key).toString();

        String msg = FuSiLingFlimApiService.payConfirm(orderId, applyKey, isChangeSeats);

        log.info(msg);

        // 解析
        outVo = JSON.parseObject(msg, FlimPayOutVo.class);

        if (outVo.isSuccess()) {
            outVo.setOrderId(orderId);
            BuyerOrder buyerOrder = this.getBaseMapper().selectById(orderId);
            buyerOrder.setFlimTicketInfo(outVo.getMsg());
            this.updateById(buyerOrder);
        }
        return outVo;
    }
}
